<?php
/*
 * Created on 21 janv. 2009
 * Created by Ludovic Reenaers
 * lreenaers@hotmail.com
 */

class Controler
{
	private $params;
	private $model;
	private $view;
	private $translator;


	function __construct()
	{
		$_SESSION['config'] = new ConfigReader();
		$this->model = new Model(null,null);
		$this->setLanguage();
		$this->translator = new DBTranslator($this->model->getFactory());
		$this->checkSession();
		$this->params=array();
		$this->getAction();
		try{
			$this->createMV();
			echo $this->view->getPage();
		}catch (Exception $e){
			echo "forbidden !!<br/>".$e->getMessage();
			echo "<br/>".$e->getTraceAsString();
		}


	}
	private function checkSession(){
			
		if(!isset($_SESSION["USER_BEAN"])){

			$_SESSION["USER_BEAN"]=$this->model->getAnonymousUser();

			
		}
		if (!isset($_SESSION['encoding'])){
			$_SESSION['encoding']='UTF-8';
		}

			
	}
	private function setLanguage(){
			$ckVal = $this->model->getLanguageIsoCookyValue();

			if(is_null($ckVal)){
					
				$_SESSION['langue'] = $this->model->getDefaultLanguageIso();
					
			}else{
					
				$_SESSION['langue'] = $ckVal;
			}
	}
	private function authorizeAction($tokenstr){
		$tmpToken = false;
			
		foreach ($_SESSION['USER_BEAN']->getProfile()->getTokens() as $token) {

			if(strtolower($token->getLabel()) == strtolower($tokenstr)){
				$tmpToken = $token;
			}
		}
			
		return $tmpToken;
	}
	private function authorizeDocument(){
		$bool = false;
		$tokens = $_SESSION['USER_BEAN']->getProfile()->getTokens();
		$forbidden = "";
		foreach ($tokens as $Token) {
			if(strtolower($Token->getLabel()) == "document#show"){
				$forbidden = explode(".", $Token->getXcept());
			}elseif (strtolower($Token->getLabel()) == "category#show") {
				$forbiddenCats = explode(".", $Token->getXcept());
			}
		}
		if($forbidden=="" || (!in_array($_SESSION['docid'], $forbidden) && !$this->isAChildOfForbiddenAncestor($forbiddenCats))){
			$bool = true;
		}
		return $bool;
	}
	private function authorizeCategory(){
		$bool = false;
		$tokens = $_SESSION['USER_BEAN']->getProfile()->getTokens();
		$forbidden = "";
		foreach ($tokens as $Token) {
			if(strtolower($Token->getLabel()) == "category#show"){
				$forbidden = explode(".", $Token->getXcept());
					
			}
		}

		if($forbidden=="" || (!in_array($_SESSION['catid'], $forbidden) && !$this->isAChildOfForbiddenAncestor($forbidden))){

			$bool = true;
		}
		return $bool;
	}
	private function isAChildOfForbiddenAncestor($forbiddenTab){
		$bool = false;
			
		foreach ($forbiddenTab as $forbiddenId) {

			if($this->model->isAncestorCategory($forbiddenId)){
					
				$bool = true;
			}
		}
		return $bool;
	}
	private function authorizeField($fieldId){
			
		$bool = true;
			
			
		return $bool;
	}
	private function checkSecurity(){

		$bool = false;

		$_SESSION['TOKEN'] = $this->authorizeAction($_SESSION['module']."#".$_SESSION['action']);
		if(is_a($_SESSION['TOKEN'], 'Token')){

			if(strtolower($_SESSION['module']) == 'document'){

				$bool = $this->authorizeDocument();
			}elseif (strtolower($_SESSION['module']) == 'category') {

				$bool = $this->authorizeCategory();

			}else{

				$bool = true;
			}
		}
		return $bool;

	}
	private function getAction()
	{

		$this->params=explode("/",substr($_SERVER["REQUEST_URI"],strlen($_SERVER["SCRIPT_NAME"])+1));

		if(count($this->params)<=1)
		{
			$_SESSION["action"]="";
			$_SESSION["module"]="";

		}
		else
		{
			$_SESSION["action"]=strtolower($this->params[2]);
			$_SESSION["module"]=strtolower($this->params[1]);
		}

		if($_SESSION["module"] == "category"){
			if(count($this->params)>=4){
				$_SESSION["catid"] = $this->params[3];
				$_SESSION["catname"] = urldecode($this->params[4]);
				$_SESSION["docid"] = '';
				$_SESSION["docname"] = '';
			}else{
				$_SESSION["catid"] = '';
				$_SESSION["catname"] = '';
				$_SESSION["docid"] = '';
				$_SESSION["docname"] = '';
			}
		}elseif ($_SESSION["module"] == "document"){
			if(count($this->params)>=4){
				$_SESSION["docid"] = $this->params[3];
				$_SESSION["docname"] = urldecode($this->params[4]);
				$_SESSION["catid"] ='';
				$_SESSION["catname"] = '';
			}else{
				$_SESSION["docid"] = '';
				$_SESSION["docname"] = '';
				$_SESSION["catid"] ='';
				$_SESSION["catname"] = '';
			}
		}elseif ($_SESSION["module"] == "user" && $_SESSION["action"] == "edit"){
			$_SESSION["docname"] = $this->translator->prefs;
			$_SESSION["catname"] = $this->translator->prefs;
		}elseif ($_SESSION["module"] == "user" && $_SESSION["action"] == "add"){
			$_SESSION["docname"] = $this->translator->register;
			$_SESSION["catname"] = $this->translator->register;
		}elseif ($_SESSION["module"] == "login" && $_SESSION["action"] == "show"){
			$_SESSION["docname"] = $this->translator->login;
			$_SESSION["catname"] = $this->translator->login;
		}elseif ($_SESSION["module"] == "homepage"){
			$_SESSION["docname"] = $this->translator->home;
			$_SESSION["catname"] = $this->translator->home;
		}
		else{
			$_SESSION["docid"] = '';
			$_SESSION["docname"] = '';
			$_SESSION["catid"] = '';
			$_SESSION["catname"] = '';
		}
	}
	function getIP() {
		$ip;
		if (getenv("HTTP_CLIENT_IP"))
		$ip = getenv("HTTP_CLIENT_IP");
		else if(getenv("HTTP_X_FORWARDED_FOR"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if(getenv("REMOTE_ADDR"))
		$ip = getenv("REMOTE_ADDR");
		else
		$ip = "UNKNOWN";
		return $ip;

	}

	function doAction(){

		$mpack="models/Model".ucfirst($_SESSION["module"]).".php";
		$vpack="views/View".ucfirst($_SESSION["module"]).".php";
		$m="Model".ucfirst($_SESSION["module"]);
		$v="View".ucfirst($_SESSION["module"]);
		$method=$_SESSION["action"];
		$bool=true;

		if(file_exists($_SERVER{'DOCUMENT_ROOT'}."/".$mpack) && file_exists($_SERVER{'DOCUMENT_ROOT'}."/".$vpack))
		{
			$this->model=new $m($this->params,$this->translator);
			if($_SESSION['USER_BEAN']->getProfile()->getLabel() <> 'anonymous'){
				$_SESSION['USER_BEAN']->setIp($this->getIP());
				$this->model->updateUserSecInfo();
			}
			$this->view=new $v($this->model,$this->translator);
			if (method_exists($this->view,$method) && $this->checkSecurity()){
				$this->view->$method($this->model->$method());
			}else{

				$bool = false;
			}

		}
		else{

			$m = new Model($this->params,$this->translator);
			$this->view=new View("",$m,"XHTML1.0T");
			$bool = false;
		}
		if(!$bool){

			$this->view->redirect($_SESSION['config']->controler.'?/homepage/show');
		}

	}
	function createMV()
	{
		$this->doAction();
	}
}
?>